package com.example.yingjiguanli_demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yingjiguanli_demo.pojo.*;
import com.example.yingjiguanli_demo.mapper.ApplicationsMapper;
import com.example.yingjiguanli_demo.service.IApplicationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yingjiguanli_demo.utils.UserUtils;
import org.apache.poi.ss.formula.functions.T;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.Action;
import java.time.LocalDateTime;
import java.util.List;

import static com.example.yingjiguanli_demo.utils.ConstantUtils.TEACHER_APPLY_WAIT;

/**
 * <p>
 * 学生申请导师表 服务实现类
 * </p>
 *
 * @author scj
 * @since 2024-12-07
 */
@Service
public class ApplicationsServiceImpl extends ServiceImpl<ApplicationsMapper, Applications> implements IApplicationsService {

    @Autowired
    private ApplicationsMapper applicationsMapper;

    @Autowired
    private UserUtils userUtils;

    @Override
    @Transactional
    public Result<T> submitApplication(
            String sessionId,
            ApplicationRequest applicationRequest) {
        // 防止XSS攻击：清理用户输入的内容
        String applicationReason = applicationRequest.getApplicationReason();
        if (applicationReason != null) {
            // 使用Jsoup清理内容，移除所有HTML标签，保留纯文本
            applicationReason = Jsoup.clean(applicationReason, Safelist.none());
            // 或者，如果需要保留一些基本标签，可以使用 Safelist.basic()
            applicationRequest.setApplicationReason(applicationReason);
        }
        // 防止XSS攻击：清理用户输入的内容
        String applicationRequestResearchInterests = applicationRequest.getResearchInterests();
        if (applicationRequestResearchInterests != null) {
            // 使用Jsoup清理内容，移除所有HTML标签，保留纯文本
            applicationRequestResearchInterests = Jsoup.clean(applicationRequestResearchInterests, Safelist.none());
            // 或者，如果需要保留一些基本标签，可以使用 Safelist.basic()
            applicationRequest.setApplicationReason(applicationRequestResearchInterests);
        }
        // 获取学生id
        int userId = userUtils.getUserId(sessionId);
        // 创建申请对象
        Applications application = new Applications();
        application.setStudentId(userId);
        application.setMentorId(applicationRequest.getMentorId());
        application.setApplicationReason(applicationRequest.getApplicationReason());
        application.setResearchInterests(applicationRequest.getResearchInterests());
        application.setStatus(TEACHER_APPLY_WAIT); // 默认状态为待处理
        application.setCreatedAt(LocalDateTime.now()); // 当前时间

        // 保存到数据库
        int insert = applicationsMapper.insert(application);
        if (insert > 0) {
            return Result.success("申请成功");
        }
        return Result.failed("申请失败");
    }

    /**
     *  * 更新申请状态
     * @param applicationId 申请id
     * @param status 状态
     * @return Result<T>
     */
    @Override
    @Transactional
    public Result<T> updateApplicationStatus(Integer applicationId, String status) {
        // 查找申请
        Applications application = applicationsMapper.selectById(applicationId);
        if (application != null) {
            // 判断是否被别的导师同意
            // 更新状态
            application.setStatus(status);
            applicationsMapper.updateById(application);
        } else {
            return Result.failed("申请不存在");
        }
        return Result.success("处理成功");
    }

    /**
     * * 获取申请
     * @param applicationId 申请id
     * @return Applications
     */
    @Override
    public Applications getApplication(Integer applicationId) {
        return applicationsMapper.selectById(applicationId);
    }

    /**
     * * 获取学生申请
     * @param sessionId sessionId
     * @return  Result<List<Applications>>
     */
    @Override
    public Result<List<ApplicationWithMentorDTO>> getApplicationBySessionId(String sessionId) {
        int userId = userUtils.getUserId(sessionId);
        List<ApplicationWithMentorDTO> applicationsWithMentorByStudentId = applicationsMapper.getApplicationsWithMentorByStudentId(userId);
        return Result.success(applicationsWithMentorByStudentId);
    }

    /**
     * * 分页查询申请
     * @param pageNum pageNum
     * @param pageSize pageSize
     * @return Result<Page<ApplicationWithStudentAndMentorDTO>>
     */
    @Override
    public Result<Page<ApplicationWithStudentAndMentorDTO>> getApplicationsPage(String sessionId,int pageNum, int pageSize) {
        Long userId = (long) userUtils.getUserId(sessionId);

        // 创建分页对象
        Page<ApplicationWithStudentAndMentorDTO> page = new Page<>(pageNum, pageSize);

        // 分页查询包含导师和学生信息的申请
        IPage<ApplicationWithStudentAndMentorDTO> applicationsPage = applicationsMapper.selectApplicationsWithStudentAndMentorPage(page,userId);

        // 将 IPage 转换为 Page
        Page<ApplicationWithStudentAndMentorDTO> resultPage = new Page<>();
        resultPage.setRecords(applicationsPage.getRecords());
        resultPage.setTotal(applicationsPage.getTotal());
        resultPage.setCurrent(applicationsPage.getCurrent());
        resultPage.setSize(applicationsPage.getSize());

        return Result.success(resultPage);
    }
}
